package com.taotao.service.impl;

import java.io.InputStream;

import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.taotao.common.result.PictureResult;
import com.taotao.common.utils.FtpUtil;
import com.taotao.common.utils.IDUtils;
import com.taotao.service.PictureService;

@Service
public class PictureServiceImpl implements PictureService {
	@Value("${FTP_SERVER_IP}")
	private String FTP_SERVER_IP;
	@Value("${FTP_SERVER_PORT}")
	private int FTP_SERVER_PORT;
	@Value("${FTP_SERVER_USERNAME}")
	private String FTP_SERVER_USERNAME;
	@Value("${FTP_SERVER_PASSWORD}")
	private String FTP_SERVER_PASSWORD;
	@Value("${FTP_BASE_PATH}")
	private String FTP_BASE_PATH;
	@Override
	public PictureResult uploadFile(MultipartFile uploadFile) throws Exception {
		String path= savePicture(uploadFile);
		PictureResult result=new PictureResult(0, "http://"+FTP_SERVER_IP+FTP_BASE_PATH+path);
		return result;
	}
	
	private String savePicture(MultipartFile uploadFile){
		String result = null;
		try {
			if(uploadFile.isEmpty())
		       return null;
			String filePath="/"+new DateTime().toString("yyyy/MM/dd");
			String originaFilename=uploadFile.getOriginalFilename();
			String newFileName=IDUtils.getImageName()+originaFilename.substring(originaFilename.lastIndexOf("."));
			@SuppressWarnings("unused")
			InputStream inputStream=uploadFile.getInputStream();
			FtpUtil.uploadFile(FTP_SERVER_IP, FTP_SERVER_PORT, FTP_SERVER_USERNAME,
					FTP_SERVER_PASSWORD, FTP_BASE_PATH, filePath, newFileName,uploadFile.getInputStream());
			result=filePath+"/"+newFileName;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}
